import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:intl/intl.dart';
import 'package:schedule_self_client/api/schedule_self_server/task.dart';
import 'package:schedule_self_client/api/schedule_self_server/task_api.dart';
import 'package:schedule_self_client/api/schedule_self_server/task_list_resp_v2.dart';
import 'package:schedule_self_client/common/simple_resp.dart';
import 'package:schedule_self_client/ui/components/task_dialog.dart';

class TaskListPageV2 extends StatefulWidget {
  const TaskListPageV2({super.key});

  @override
  State<TaskListPageV2> createState() => _TaskListPageV2State();
}

class _TaskListPageV2State extends State<TaskListPageV2>
    with AutomaticKeepAliveClientMixin<TaskListPageV2> {
  final List<Task> _completeTasks = [];
  final List<Task> _incompleteTasks = [];
  bool _isLoading = false;
  bool _completeCollapseFlag = true;
  bool _incompleteCollapseFlag = true;

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    _loadTaskList();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        title: const Text('全部'),
      ),
      body: RefreshIndicator(
        triggerMode: RefreshIndicatorTriggerMode.anywhere,
        onRefresh: _loadTaskList,
        child: ScrollConfiguration(
          behavior: ScrollConfiguration.of(context).copyWith(dragDevices: {
            PointerDeviceKind.touch,
            PointerDeviceKind.mouse,
          }),
          child: CustomScrollView(
            slivers: [
              SliverToBoxAdapter(
                child: InkWell(
                  onTap: () {
                    setState(() {
                      _incompleteCollapseFlag = !_incompleteCollapseFlag;
                    });
                  },
                  child: SizedBox(
                    height: 36,
                    child: Row(
                      children: [
                        _incompleteCollapseFlag
                            ? const Icon(Icons.arrow_drop_down)
                            : const Icon(Icons.arrow_right),
                        Expanded(
                          child: Text(
                            '未完成',
                            style: Theme.of(context).textTheme.titleLarge,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
              if (_incompleteCollapseFlag)
                SliverList(
                  delegate: SliverChildBuilderDelegate((context, index) {
                    return _buildTaskCard(_incompleteTasks[index]);
                  }, childCount: _incompleteTasks.length),
                ),
              SliverToBoxAdapter(
                child: InkWell(
                  onTap: () {
                    setState(() {
                      _completeCollapseFlag = !_completeCollapseFlag;
                    });
                  },
                  child: SizedBox(
                    height: 36,
                    child: Row(
                      children: [
                        _completeCollapseFlag
                            ? const Icon(Icons.arrow_drop_down)
                            : const Icon(Icons.arrow_right),
                        Expanded(
                          child: Text(
                            '已完成',
                            style: Theme.of(context).textTheme.titleLarge,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
              if (_completeCollapseFlag)
                SliverList(
                  delegate: SliverChildBuilderDelegate((context, index) {
                    return _buildTaskCard(_completeTasks[index]);
                  }, childCount: _completeTasks.length),
                ),
            ],
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          showDialog(
              context: context,
              builder: (context) => TaskDialog(
                    okCallback: _loadTaskList,
                  ));
        },
        shape: const CircleBorder(),
        child: const Icon(Icons.add),
      ),
    );
  }

  Widget _buildTaskCard(Task task) {
    return Card(
      color: task.taskCategoryDto == null
          ? null
          : Color(int.parse(task.taskCategoryDto!.color)),
      child: Row(
        children: [
          // IconButton(onPressed: () {}, icon: Icon(Icons.check_circle_outline)),
          IconButton(
              onPressed: () {
                _taskCompleteFlagChange(task);
              },
              icon: task.isComplete()
                  ? const Icon(Icons.check_circle_outline)
                  : const Icon(Icons.circle_outlined)),
          Expanded(
            child: InkWell(
              onLongPress: () {
                showDialog(
                  context: context,
                  builder: (context) => AlertDialog(
                    title: const Text('确定删除么？'),
                    actions: [
                      TextButton(
                          onPressed: () {
                            Navigator.of(context).pop();
                          },
                          child: const Text('取消')),
                      ElevatedButton(
                          onPressed: () async {
                            _batchDeleteTasks([task.id]);
                            Navigator.of(context).pop();
                          },
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Theme.of(context).primaryColor,
                          ),
                          child: const Text(
                            '确定',
                            style: TextStyle(color: Colors.white),
                          )),
                    ],
                  ),
                );
              },
              onTap: () {
                GoRouter.of(context).push('/task_detail', extra: task.id);
              },
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const SizedBox(
                    height: 8,
                  ),
                  Text(
                    task.name,
                    style: TextStyle(
                        color: task.isComplete() ? Colors.grey : Colors.black,
                        decoration: task.isComplete()
                            ? TextDecoration.lineThrough
                            : null),
                  ),
                  const SizedBox(
                    height: 4,
                  ),
                  Row(
                    children: [
                      const Icon(Icons.calendar_today, size: 16),
                      const SizedBox(width: 4),
                      Text(task.deadline != null
                          ? _showCompleteTime(task.deadline!)
                          : '未设置截止日期'),
                    ],
                  ),
                  const SizedBox(
                    height: 8,
                  )
                ],
              ),
            ),
          ),
          IconButton(onPressed: () {}, icon: const Icon(Icons.star_border))
        ],
      ),
    );
  }

  _batchDeleteTasks(List<int> idList) async {
    SimpleResp simpleResp = await TaskApi.batchDeleteTasks(idList);
    if (simpleResp.success) {
      _loadTaskList();
    }
  }

  String _showCompleteTime(String completeTimeStr) {
    DateTime completeTime = DateTime.parse(completeTimeStr);
    DateFormat dateFormat =
        DateFormat('M月d日 E', Localizations.localeOf(context).languageCode);
    return dateFormat.format(completeTime);
  }

  _taskCompleteFlagChange(Task task) async {
    SimpleResp simpleResp = await TaskApi.taskCompleteFlagChange(task.id);
    if (simpleResp.success) {
      setState(() {
        _loadTaskList();
      });
    }
  }

  Future<void> _loadTaskList() async {
    if (_isLoading) {
      return;
    }
    setState(() {
      _isLoading = true;
    });
    try {
      TaskListRespV2 taskListRespV2 = await TaskApi.getTasksV2();
      _incompleteTasks.clear();
      _incompleteTasks
          .addAll(taskListRespV2.data.where((task) => !task.isComplete()));
      _completeTasks.clear();
      _completeTasks
          .addAll(taskListRespV2.data.where((task) => task.isComplete()));
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }
}
